<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix process-header flex width100p">
        <div class="title flex-auto">{{ processTitle }}<span class="ml10 sub-title">{{ subTitle }}</span></div>
        <div class="btn-list flex flex-row align-center mr20 bg-white">

          <div v-if="processStructureValue.workOrder" class="pl15 pr15">
            上报人：<span class="primary-color">{{
              processStructureValue.workOrder.createdName
            }}</span>
          </div>
          <div v-if="processStructureValue.workOrder" class="pl15 pr15" style="margin-right:180px">
            最新状态：<span class="primary-color">{{
              processStructureValue.workOrder.current_state_name
            }}</span>
            <span
              v-if="processStructureValue.workOrder.principals != ''"
              class="ml20"
            >当前处理人：</span>
            <span
              v-if="processStructureValue.workOrder.principals != ''"
              class="danger-color"
            >【{{ processStructureValue.workOrder.principals }}】</span>
          </div>
          <div class="flex fixed-btn bg-white" style="right: 30px;">
            <el-button type="" size="mini" @click="backPage">
              返 回
            </el-button>
            <el-button v-if="!pdfLoading" type="primary" size="mini" @click="outPutPdfFn()">
              导出PDF
            </el-button>
            <el-button v-else type="primary" size="mini" :loading="true">
              正在导出
            </el-button>
          </div>
        </div>

      </div>
      <div class="flex">
        <div id="pdfHtml" class="text item flex-auto width0">
          <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" />
          <template v-for="(tplItem, tplIndex) in processStructureValue.tpls">
            <!-- <fm-generate-form v-show="currentNode.hideTpls===undefined ||
              currentNode.hideTpls===null ||
              currentNode.hideTpls.indexOf(tplItem.id)===-1" :key="tplIndex" :ref="'generateForm-'+tplItem.id" :preview="currentNode.hideTpls===undefined ||
              currentNode.hideTpls===null ||
              currentNode.hideTpls.indexOf(tplItem.id)===-1?false:true" :remote="remoteFunc" :value="tplItem.form_data" :data="tplItem.form_structure" :disabled="currentNode.readonlyTpls===undefined ||
              currentNode.readonlyTpls===null ||
              currentNode.readonlyTpls.indexOf(tplItem.id)===-1?null:true" /> -->
            <DetailComp :mid="tplItem.mid" :form-data="tplItem.form_data" :create-time="processStructureValue.workOrder.create_time" :disposetpls="processStructureValue.disposetpls" />
          </template>
          <div class="height32" />
          <div class="item-excel">
            <div class="primary-header clearfix flex flex-row align-center">
              <div class="line" />
              <span class="font18 ml10 flex-auto">审批历史</span>
            </div>
            <div class="text item pt10 pb10 pl10 pr10">
              <el-table :data="circulationHistoryList" border style="width: 100%" stripe max-height="600">
                <el-table-column prop="id" label="#" align="center" type="index" width="70" />
                <el-table-column prop="state" label="任务名称" align="center" />
                <el-table-column prop="processor" label="处理人" align="center" />
                <el-table-column prop="status" label="审批操作" align="center">
                  <template slot-scope="scope">
                    <div v-if="scope.row.status == 1">
                      审批通过
                    </div>
                    <div v-if="scope.row.status == 2">
                      提交成功
                    </div>
                    <div v-if="scope.row.status == 0">
                      审批退回
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="remarks" label="处置意见" align="center" :show-overflow-tooltip="true">
                  <template slot-scope="scope">
                    {{
                      formatFullMessage(scope.row.remarks)
                    }}
                  </template>
                </el-table-column>
                <el-table-column prop="cost_duration" label="耗时" align="center">
                  <template slot-scope="scope">
                    <div>{{ getDuration(scope.row.cost_duration) }}</div>
                  </template>
                </el-table-column>
                <!-- <el-table-column prop="circulation" label="流转" align="center" /> -->
                <el-table-column prop="create_time" label="处理时间" align="center" width="180" />
                <el-table-column prop="status" label="状态" align="center" width="90">
                  <template slot-scope="scope">
                    <div v-if="scope.row.status == 3" class="warning-color">
                      待处理
                    </div>
                    <div v-else class="primary-color">
                      已处理
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <div class="right width300 ml10">
          <el-card class="box-card history-box mb20 history-baqsj">
            <div slot="header" class="clearfix flex flex-row align-center height32">
              <div class="line" />
              <span class="font16 ml10 flex-auto">审批节点</span>
            </div>
            <vue-scroll :ops="ops">
              <div class="timeline">
                <el-timeline v-if="timelineShow">
                  <el-timeline-item v-for="item in timeLine" :key="item.id" :hide-timestamp="true" icon="el-icon-my-time" color="#277fd6" size="large">
                    <div class="flex flex-column">
                      <div class="time">
                        <span class="text">{{ item.create_time }}</span>
                        <el-tag :type="getHistoryTag(item)" effect="dark" size="small" class="stateTag ml10">
                          {{ getHistoryState(item) }}
                        </el-tag>
                      </div>
                      <div v-if="item.status == 2 && item.target != ''" class="info">
                        <span class="label">上报人：</span><span class="detail">{{ item.processor }}</span>
                      </div>
                      <div v-else class="info">
                        <span class="label">审批人：</span><span class="detail">{{ item.processor }}</span>
                      </div>
                      <div class="info">
                        <span class="label">审批节点：</span><span class="detail">{{ item.state }}</span>
                      </div>
                      <div v-if="item.status == 2 && item.target != ''" class="info flex flex-row" />
                      <div v-else class="info flex flex-row">
                        <span class="label">处置意见：</span><span class="detail flex-auto">{{
                          formatFullMessage(item.remarks)
                        }}</span>
                      </div>
                      <div v-if="getModifyText(item.remarks)" class="info flex flex-row">
                        <span class="label">分配部门：</span><span class="detail flex-auto">{{
                          getModifyText(item.remarks)
                        }}</span>
                      </div>
                    </div>
                  </el-timeline-item>
                </el-timeline>
                <div v-else class="empty-time mt50 mb20">
                  <img src="@/assets/empty.png" alt="">
                  <span>暂时没有审批内容</span>
                </div>
              </div>
            </vue-scroll>
          </el-card>
        </div>
      </div>
      <hr style="background-color: #d9d9d9; border:0; height:1px;margin-bottom: 50px;">
    </el-card>
  </div>
</template>
<script>
import Vue from 'vue'
import { Message, Loading } from 'element-ui'
import {
  GenerateForm
} from '@/components/VueFormMaking'
import 'form-making/dist/FormMaking.css'
Vue.component(GenerateForm.name, GenerateForm)
import { getDuration } from '@/utils/costum'
import {
  processStructure
} from '@/api/baqsj/work-order'
import { listAllUser } from '@/api/system/sysuser'
import { getOrdinaryDeptList, bqDeptList } from '@/api/system/dept'
import DetailComp from '../components/detail/index.vue'
import { formatFullMessage, getModifyText } from '@/utils/format'
export default {
  name: 'BaqsjReview',
  components: {
    DetailComp
  },
  data() {
    return {
      formatFullMessage,
      getModifyText,
      bqTrees: [],
      getDuration,
      pdfLoading: false,
      loadingFull: null,
      timelineShow: false,
      timeLine: [],
      ops: {
        vuescroll: {
          mode: 'native',
          sizeStrategy: 'percent',
          detectResize: true,
          locking: true
        },
        scrollPanel: {
          maxHeight: 800
        },
        bar: {
          background: '#277fd6',
          size: '3px',
          keepShow: true
        },
        rail: {
          background: '#E0E8F0',
          opacity: 1,
          size: '3px',
          specifyBorderRadius: false,
          gutterOfEnds: '50px',
          gutterOfSide: '0px',
          keepShow: false
        }
      },
      processTitle: '',
      subTitle: '',
      processId: '',
      circulationHistoryList: [],
      processStructureValue: {},
      workOrdeInfo: {
        id: null,
        status: 1
      },
      draftDisabled: false,
      tpls: [],
      newTpls: [],
      ruleForm: {
        title: '',
        priority: 1,
        process: '',
        classify: '',
        state: [],
        source: '',
        source_state: '',
        process_method: '',
        tpls: {
          form_structure: [],
          form_data: []
        },
        newTpls: {},
        tasks: []
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        priority: [
          { required: true, message: '请选择优先级', trigger: 'blur' }
        ]
      },
      remoteFunc: {
        // 获取用户列表
        async userList(resolve) {
          const res = await listAllUser({})
          const options = res.data
          resolve(options)
        },
        async deptTreeList(resolve) {
          const res = await getOrdinaryDeptList()
          resolve(res.data)
        },
        async bqTreeList(resolve) {
          const res = await bqDeptList()
          resolve(res.data)
        }
      }
    }
  },
  async created() {
    this.processId = parseInt(this.$route.query.processId)
    this.ruleForm.workOrderId = parseInt(this.$route.query.workOrderId)
    await this.getBqTreeList()
    this.getProcessNodeList()
  },
  methods: {
    async getBqTreeList() {
      const res = await bqDeptList()
      if (res.data) {
        this.bqTrees = res.data
      }
    },
    outPutPdfFn() {
      const vm = this
      const A4_WIDTH = 592.28
      const A4_HEIGHT = 841.89 // $myLoading 自定义等待动画组件，实现导出事件的异步等待交互
      this.pdfLoading = true
      this.loadingFull = Loading.service({
        target: document.querySelector('.app-wrapper'),
        lock: true,
        text: '正在导出中，请稍后……',
        background: 'rgba(0, 0, 0, 0.7)',
        customClass: 'zIndex9999'
      })
      vm.$nextTick(() => {
        // dom的id。
        const target = document.getElementById('pdfHtml')
        const pageHeight = target.scrollWidth / A4_WIDTH * A4_HEIGHT
        // 获取分割dom，此处为class类名为item的dom
        const lableListID = document.getElementsByClassName('item-excel')
        // 进行分割操作，当dom内容已超出a4的高度，则将该dom前插入一个空dom，把他挤下去，分割
        for (let i = 0; i < lableListID.length; i++) {
          const multiple = Math.ceil((lableListID[i].offsetTop + lableListID[i].offsetHeight / 2) / pageHeight)
          if (this.isSplit(lableListID, i, multiple * pageHeight)) {
            const divParent = lableListID[i].parentNode
            // 获取该div的父节点
            const newNode = document.createElement('div')
            newNode.className = 'emptyDiv'
            newNode.style.background = '#ffffff'
            const _H = multiple * pageHeight - (lableListID[i].offsetTop + lableListID[i].offsetHeight)
            newNode.style.height = _H + 30 + 'px'
            newNode.style.width = '100%'
            const next = lableListID[i].nextSibling
            // 获取div的下一个兄弟节点
            // // 判断兄弟节点是否存在
            if (next) {
              // 存在则将新节点插入到div的下一个兄弟节点之前，即div之后
              divParent.insertBefore(newNode, next)
            } else {
              // 不存在则直接添加到最后,appendChild默认添加到divParent的最后
              divParent.appendChild(newNode)
            }
          }
        }
        // 传入title和dom标签，此处是 #content// 异步函数，导出成功后处理交互
        this.getPdf(`${this.processStructureValue.workOrder.title}`, '#pdfHtml').then(() => {}).catch(() => {})
        setTimeout(() => {
          this.loadingFull.close()
          this.pdfLoading = false
        }, 2000)
        this.pdfLoading = false
      })
    },
    isSplit(nodes, index, pageHeight) {
      // 计算当前这块dom是否跨越了a4大小，以此分割
      if (nodes[index].offsetTop + nodes[index].offsetHeight < pageHeight && nodes[index + 1] &&
        nodes[index + 1].offsetTop + nodes[index + 1].offsetHeight > pageHeight) { return true }
      return false
    },
    getHistoryState(item) {
      if (item.circulation == '结束') {
        return '处置完成'
      } else if (item.circulation == '已撤回') {
        return '已撤回'
      } else {
        if (item.status == 2) {
          if (item.target != '') {
            return '提交上报'
          } else {
            return '转交'
          }
        } else if (item.status == 0) {
          return '审批退回'
        } else {
          return '审批通过'
        }
      }
    },
    getHistoryTag(item) {
      if (item.circulation == '结束') {
        return 'success'
      } else if (item.circulation == '已撤回') {
        return 'danger'
      } else {
        if (item.status == 2) {
          if (item.target != '') {
            return ''
          } else {
            return 'warning'
          }
        } else if (item.status == 0) {
          return 'danger'
        } else {
          return 'success'
        }
      }
    },
    backPage() {
      // this.$router.push({ path: '/baqsj/apply', query: {} })
      this.$router.go(-1)
    },
    getProcessNodeList() {
      processStructure({
        processId: this.$route.query.processId,
        workOrderId: this.ruleForm.workOrderId
      }).then(response => {
        this.processStructureValue = response.data
        this.newTpls = response.data.tpls
        this.currentNode = this.processStructureValue.nodes[0]
        this.subTitle = this.processStructureValue.process.name
        this.processTitle = this.processStructureValue.process.category
        this.circulationHistoryList = this.processStructureValue.circulationHistory
        if (this.circulationHistoryList.length > 0) {
          this.timelineShow = true
          this.timeLine = this.circulationHistoryList
        }
      })
    }
  }
}

</script>
<style lang="scss" scoped>
.process-header {
  height: 50px;

  .title {
    font-size: 25px;
    font-weight: 600;

  }

  .sub-title {
    font-size: 19px;
    vertical-align: bottom;
    padding-left: 10px;
    color: #555;
  }
}

.history-box {
    border-radius: 15px;
    .line {
      height: 22px;
      width: 5px;
      background: #277fd6;
    }
  }

  .empty-time {
    display: flex;
    align-items:center;
    flex-direction: column;
    justify-content: center;
    img {
      width:200px;
    }
  }

</style>
